package dyyx;

import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;


public abstract class GsonUtil {

    private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";


	public static String toString(Object obj, boolean pretty) {
		if(obj==null){
			return null;
		}
		if(obj instanceof String){
			return (String)obj;
		}
		
		GsonBuilder gb = new GsonBuilder();
		gb.setDateFormat(DATE_TIME_FORMAT);
		if(pretty){
			gb.setPrettyPrinting();
		}

		return gb.create().toJson(obj);
		
	}
	
	
	public static <T> T toObject(String str,Class<T> clazz){
		if(str==null){
			return null;
		}
		if(clazz.equals(String.class)){
			return (T)str;
		}
		GsonBuilder gb = new GsonBuilder();

		
		return gb.create().fromJson(str, clazz);
	}
	
	
    public static <T> T toObject(String str, TypeToken<T> type)throws Exception{
    	if(str==null){
			return null;
		}
        GsonBuilder gb = new GsonBuilder();

		return gb.create().fromJson(str, type.getType());
    }


}
